#include <net.h>
#include <os/string.h>
#include <screen.h>
#include <emacps/xemacps_example.h>
#include <emacps/xemacps.h>

#include <os/sched.h>
#include <os/mm.h>

EthernetFrame rx_buffers[RXBD_CNT];
EthernetFrame tx_buffer;
uint32_t rx_len[RXBD_CNT];

int net_poll_mode;

volatile int rx_curr = 0, rx_tail = 0;

long do_net_recv(uintptr_t addr, size_t length, int num_packet, size_t* frLength)
{
    int cur_num_packet = num_packet;//num_packet是总的收包数，cur_num_packet是剩余的包数目
    while(cur_num_packet > 0)
    {
        int num = (cur_num_packet > 32) ? 32 : cur_num_packet;//num是一次接收过程（硬件）收的包数目,一次最多32个包
        printk("\n--------begin num = %d\n", num);
        EmacPsRecv(&EmacPsInstance, 
                0, num,kva2pa(rx_buffers)); //传的地址都是物理地址
        printk("\n-------send num = %d\n", num);
        EmacPsWaitRecv(&EmacPsInstance,
                num, rx_len);
        // Copy to user
        for (int i = 0; i < num; i++){//将包长度传回用户区域
            kmemcpy(addr, rx_buffers + i, rx_len[i]);
            *frLength = rx_len[i];
            frLength ++;
            addr += rx_len[i];
        }
        cur_num_packet -= 32;//接收完成，剩余包数目减32
        printk("\n-------finish num = %d\n", cur_num_packet);
    }
    return 1;
}

void do_net_send(uintptr_t addr, size_t length)
{
    // TODO:
    kmemcpy(&tx_buffer, addr, length);
    EmacPsSend(&EmacPsInstance,0,length,kva2pa(&tx_buffer));//传物理地址
    EmacPsWaitSend(&EmacPsInstance);
    // send all packet
    // maybe you need to call drivers' send function multiple times ?
}

void do_net_irq_mode(int mode)
{
    // TODO:
    // turn on/off network driver's interrupt mode
    set_irq_mode(&EmacPsInstance, mode);
}
